<template>
	<view class="profile-container">
		<view class="avatar-row">
			<button open-type="chooseAvatar" @chooseavatar="onChooseAvatar" class="avatar-button">
				<image :src="http.baseUrl + form.avatarUrl" class="small-avatar"></image>
			</button>
		</view>

		<view class="form-row">
			<text class="label">昵称</text>
			<input class="input" type="nickname" @input="handleNicknameInput" v-model.trim="form.nickName"
				placeholder="请输入昵称" />
		</view>

		<view class="form-row">
			<text class="label">电话</text>
			<input class="input" v-model.trim="form.phone" placeholder="请输入联系电话" type="number" />
		</view>

		<view class="actions">
			<button @click="save" class="save-btn">保存</button>
		</view>
	</view>
</template>

<script>
	import {
	getUser
} from '@/https/auth.js'
import {
	updateUser,
	uploadAvatar
} from '@/https/user.js'
import http from '@/https/http.js'

	export default {
		data() {
			return {
				form: {
					nickName: '',
					avatarUrl: '',
					phone: ''
				}
			}
		},
		computed: {
			// 将 http 模块暴露到实例上，使模板能够访问
			http() {
				return http;
			}
		},
		mounted() {
			const u = getUser() || {}
			this.form.nickName = u.nickName || u.name || ''
			this.form.avatarUrl = u.avatarUrl || u.avatar || ''
			this.form.phone = u.phone || u.mobile || ''
		},
		methods: {
			chooseAvatar: async function() {
				try {
					const res = await uni.chooseImage({
						count: 1
					})
					if (res && res.tempFilePaths && res.tempFilePaths[0]) {
						// 简化处理：直接使用临时路径作为 avatarUrl，本地展示；若需上传到后端，请在这里上传然后用返回的 URL
						this.form.avatarUrl = res.tempFilePaths[0]
					}
				} catch (e) {
					console.warn('chooseImage failed', e)
					uni.showToast({
						title: '选择头像失败',
						icon: 'none'
					})
				}
			},

			handleNicknameInput: function(e) {
				this.form.nickName = e.detail.value;
			},

			onChooseAvatar: async function(e) {
				// 获取临时文件路径
				const tempFilePath = e && e.detail && (e.detail.avatarUrl || (e.detail.tempFilePaths && e.detail
					.tempFilePaths[0]));

				if (!tempFilePath) {
					// 回退：调用 chooseImage 获取临时路径（兼容不同平台）
					try {
						const res = await uni.chooseImage({
							count: 1
						});
						if (res && res.tempFilePaths && res.tempFilePaths[0]) {
							this.form.avatarUrl = res.tempFilePaths[0];
						}
					} catch (err) {
						console.warn('chooseImage fallback failed', err);
						uni.showToast({
							title: '选择头像失败',
							icon: 'none'
						});
					}
					return;
				}

				// 先显示本地临时图片
				this.form.avatarUrl = tempFilePath;

				uni.showLoading({
					title: '上传头像...'
				});
				try {
					// 使用专门的uploadAvatar函数处理头像上传
					// 现在该函数接收临时文件路径，使用uni.uploadFile上传文件
					const avatarUrl = await uploadAvatar(tempFilePath);

					// 更新用户信息接口保存头像地址
					try {
						await updateUser({
							avatarUrl: avatarUrl
						});
					} catch (upErr) {
						// 即使更新用户接口失败，也把 avatarUrl 显示为服务器地址，提示用户稍后重试保存
						console.warn('更新用户信息失败（保存后）', upErr);
					}

					// 更新本地显示为服务器返回的地址
					this.form.avatarUrl = avatarUrl;
					uni.showToast({
						title: '上传成功',
						icon: 'success'
					});
				} catch (err) {
					console.error('上传头像失败', err);
					// 提取错误信息，如果有明确错误信息则显示，否则显示默认错误
					const errorMsg = err.message || '上传头像失败';
					uni.showToast({
						title: errorMsg,
						icon: 'none'
					});
					// 保持显示本地临时图片，让用户可以重试
				} finally {
					uni.hideLoading();
				}
			},

			save: async function() {
				if (!this.form.nickName) {
					uni.showToast({
						title: '请输入昵称',
						icon: 'none'
					})
					return
				}
				uni.showLoading({
					title: '保存中...'
				})
				try {
					await updateUser({
						nickName: this.form.nickName,
						avatarUrl: this.form.avatarUrl,
						phone: this.form.phone
					})
					// 更新本地缓存中的 user 对象，确保昵称/头像/电话是最新的
					try {
						const cachedUser = uni.getStorageSync('user') || {}
						// 仅在表单有值时覆盖缓存字段，保留其它字段
						if (this.form.nickName) cachedUser.nickName = this.form.nickName
						if (this.form.avatarUrl) cachedUser.avatarUrl = this.form.avatarUrl
						if (this.form.phone) cachedUser.phone = this.form.phone
						uni.setStorageSync('user', cachedUser)
						// 广播更新事件，通知其他页面刷新
						try {
							if (typeof uni !== 'undefined' && uni.$emit) {
								uni.$emit('user:updated', cachedUser)
							}
						} catch (emitErr) {
							console.warn('emit user:updated failed', emitErr)
						}
					} catch (e) {
						console.warn('更新本地缓存 user 失败', e)
					}
					uni.showToast({
						title: '保存成功',
						icon: 'success'
					})
					// 可返回上一页
					setTimeout(() => {
						uni.navigateBack()
					}, 600)
				} catch (err) {
					console.error('保存失败', err)
					uni.showToast({
						title: '保存失败',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			}
		}
	}
</script>

<style scoped>
	.profile-container {
		padding: 30rpx;
	}

	.avatar-row {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 30rpx;
		padding: 20rpx 0;
	}

	.avatar-button {
		width: 120rpx;
		height: 120rpx;
		padding: 0;
		background: transparent;
		border: none;
		line-height: 120rpx;
		overflow: hidden;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.small-avatar {
		width: 120rpx;
		height: 120rpx;
		border-radius: 60rpx;
	}

	/* 移除默认按钮样式 */
	.avatar-button::after {
		content: none;
	}

	.avatar-actions {
		margin-left: 30rpx;
	}

	.form-row {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 20rpx;
	}

	.label {
		width: 120rpx;
		color: #333;
	}

	.input {
		flex: 1;
		padding: 12rpx;
		border-radius: 8rpx;
		background: #fff;
	}

	.actions {
		margin-top: 40rpx;
	}

	.save-btn {
		width: 100%;
		background: #007aff;
		color: #fff;
		padding: 20rpx;
		border-radius: 12rpx;
	}
</style>